import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import QtQuick.Dialogs 1.3
import com.RspInterface 1.0
import com.ComboData 1.0

Item {
    property var tabName
    property string listName: "RiskTryCalc"
    property bool bInital: false
    property bool bChangeWidth: false

    property string paramCalc
    property int focusRow: -1
    property int focusCol: -1
    property bool isWriteable: false
    property ComboData custGradeModel: g_MainQuo.getCustGradeByBranchs("")

    ColumnLayout {
        anchors.fill: parent
        RowLayout {
            anchors.top: parent.top
            anchors.topMargin: 5
            anchors.left: parent.left
            anchors.leftMargin: 20
            anchors.right: parent.right
            anchors.rightMargin: 20
            Layout.preferredHeight: 40
            Layout.alignment: Qt.AlignHCenter
            Text {
                text: "试算类型:"
                Layout.alignment: Qt.AlignHCenter
            }

            ComboBox {
                id: calcType
                Layout.preferredWidth: 90
                Layout.alignment: Qt.AlignHCenter
                model: ["客户", "客户级别", "代理机构", "账户类型"]

                onCurrentIndexChanged: {
                    console.log("calcType sel " + currentIndex)
                    if (currentIndex == 0) {
                        acct_No.visible = true
                        calcObj.visible = false
                    } else {
                        acct_No.visible = false
                        calcObj.visible = true
                        //                        calcValueDrop.clear()
                        if (1 == currentIndex) {
                            //calcObj.model = g_MainQuo.getCustGradeByBranchs("") 第一次切换到客户级别，点击风险试算会出各种问题，需要第二次切换到客户级别才正常,诡异
                            //                            calcObj.model = null
                            calcObj.model = custGradeModel //g_MainQuo.getCustGradeByBranchs("")
                        } else if (2 == currentIndex) {
                            calcObj.model = g_MainQuo.getMyBranchs()
                        } else if (3 == currentIndex) {
                            calcObj.model = acctTypeModel2
                        }
                    }
                }
            }
            Item {
                Layout.preferredWidth: 25
            }
            Text {
                text: "试算类型值:"
                Layout.alignment: Qt.AlignHCenter
            }
            TextField {
                Layout.preferredWidth: 85
                id: acct_No
                Layout.alignment: Qt.AlignHCenter
                //                text: acctNo
                placeholderText: "客户号"
            }
            ComboBox {
                id: calcObj
                Layout.alignment: Qt.AlignHCenter
                //                model: calcValueDrop
            }

            Item {
                Layout.fillWidth: true
            }

            Button {
                text: "风险试算"
                Layout.alignment: Qt.AlignHCenter
                onClicked: {
                    var req
                    if (3 == calcType.currentIndex) {
                        req = "#acct_type=" + calcObj.model.get(
                                    calcObj.currentIndex).acct_type
                    } else if (0 == calcType.currentIndex) {
                        if (acct_No.text.length === 0) {
                            tipInput.text = "请填写试算类型值!"
                            tipInput.open()
                            return
                        }

                        req = "#acct_no=" + acct_No.text
                    } else if (1 == calcType.currentIndex) {
                        console.log("cust grade " + calcObj.model.get(
                                        calcObj.currentIndex))
                        req = "#cust_type=" + calcObj.model.get(
                                    calcObj.currentIndex)
                    } else if (2 == calcType.currentIndex) {
                        req = "#branch_id=" + calcObj.model.get(
                                    calcObj.currentIndex)
                    }

                    console.log(calcType.currentIndex + " req=" + req)
                    req += "#instid="
                    for (var k = 0; k < calcParaModel.count; k++) {

                        req += calcParaModel.get(k).prod_code
                        req += "｜"
                        req += calcParaModel.get(k).now_price
                        req += "｜"
                        req += calcParaModel.get(k).exch_long_rate
                        req += "｜"
                        req += calcParaModel.get(k).exch_short_rate
                        req += "｜"
                        req += calcParaModel.get(k).mem_long_rate
                        req += "｜"
                        req += calcParaModel.get(k).mem_short_rate
                        req += "｜∧"
                    }

                    paramCalc = req

                    freshResult()
                    //                    listResult.tableList.model = rsp.getAlmModel("cal_result")
                }
            }
            Item {
                Layout.preferredWidth: 40
            }
        }
        GroupBox {
            id: paraG
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            title: "试算参数"

            TableView {
                id: propertyList
                model: calcParaModel
                //                property PropertyInfo selectedItem: null
                anchors.fill: parent

                TableViewColumn {
                    role: "prod_code"
                    title: qsTr("合约代码")
                    width: propertyList.width * 0.099
                }
                TableViewColumn {
                    role: "now_price"
                    title: qsTr("合约价格")
                    width: propertyList.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    role: "exch_long_rate"
                    title: qsTr("调整交易所保证金率(多仓)")
                    width: propertyList.width * 0.2
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    role: "exch_short_rate"
                    title: qsTr("调整交易所保证金率(空仓)")
                    width: propertyList.width * 0.2
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    role: "mem_long_rate"
                    title: qsTr("调整会员保证金率(多仓)")
                    width: propertyList.width * 0.2
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    role: "mem_short_rate"
                    title: qsTr("调整会员保证金率(空仓)")
                    width: propertyList.width * 0.2
                    horizontalAlignment: Text.AlignRight
                }
                Component.onCompleted: {
                    var almName = "quotaion_result"
                    var rsp1 = g_MainQuo.queryProdPrice("#prod_code=Ag(T+D)#")
                    addCalcPara(rsp1.getAlmString(almName, 0, 0),
                                rsp1.getAlmString(almName, 0, 1))
                    var rsp2 = g_MainQuo.queryProdPrice("#prod_code=Au(T+D)#")
                    addCalcPara(rsp2.getAlmString(almName, 0, 0),
                                rsp2.getAlmString(almName, 0, 1))
                    var rsp3 = g_MainQuo.queryProdPrice("#prod_code=Au(T+N1)#")
                    addCalcPara(rsp3.getAlmString(almName, 0, 0),
                                rsp3.getAlmString(almName, 0, 1))
                    var rsp4 = g_MainQuo.queryProdPrice("#prod_code=Au(T+N2)#")
                    addCalcPara(rsp4.getAlmString(almName, 0, 0),
                                rsp4.getAlmString(almName, 0, 1))
                    var rsp5 = g_MainQuo.queryProdPrice("#prod_code=mAu(T+D)#")
                    addCalcPara(rsp5.getAlmString(almName, 0, 0),
                                rsp5.getAlmString(almName, 0, 1))
                }

                onClicked: {


                    //                    selectedItem = model[row]
                }
                rowDelegate: Rectangle {
                    height: 22
                }

                itemDelegate: editableDelegate

                //                itemDelegate: {
                //                    if (isWriteable)
                //                        return editableDelegate
                //                    return readOnlyDelegate
                //                }
                Component {
                    id: editableDelegate
                    Item {
                        Rectangle {
                            anchors.fill: parent
                            border.width: 1
                            border.color: "gray"
                            color: (focusRow === styleData.row
                                    && focusCol === styleData.column
                                    && !isWriteable) ? "#FF3399FF" : "white"
                            visible: focusRow !== styleData.row
                                     || focusCol !== styleData.column
                                     || !isWriteable
                            Text {
                                id: staticT
                                //                                width: parent.width
                                //                                anchors.margins: 4//anchors没有设好会让horizontalAlignment看起来失效
                                anchors.left: parent.left
                                anchors.leftMargin: 2
                                anchors.right: parent.right
                                anchors.rightMargin: 2
                                anchors.verticalCenter: parent.verticalCenter
                                elide: styleData.elideMode
                                text: styleData.value
                                horizontalAlignment: styleData.textAlignment
                            }
                            MouseArea {
                                anchors.fill: parent
                                onClicked: {
                                    if (focusRow === styleData.row
                                            && focusCol === styleData.column
                                            && 0 !== styleData.column) {
                                        isWriteable = true
                                    } else {
                                        isWriteable = false
                                    }

                                    focusRow = styleData.row
                                    focusCol = styleData.column
                                    console.log("click [" + focusRow + "," + focusCol + "]")
                                }
                            }
                        }
                        Loader {
                            // Initialize text editor lazily to improve performance
                            id: loaderEditor
                            anchors.fill: parent
                            anchors.margins: 2
                            sourceComponent: (focusRow === styleData.row
                                              && focusCol === styleData.column
                                              //                                              && styleData.column !== 0
                                              && isWriteable) ? editor : null

                            Component {
                                id: editor
                                TextInput {
                                    id: textinput

                                    color: styleData.textColor
                                    text: styleData.value
                                    selectByMouse: true
                                    verticalAlignment: Text.AlignVCenter

                                    Component.onCompleted: {
                                        textinput.forceActiveFocus()
                                        selectAll()
                                    }
                                    onEditingFinished: {
                                        console.log("onEditingFinished")
                                        staticT.text = textinput.text
                                        calcParaModel.setProperty(
                                                    styleData.row,
                                                    propertyList.getColumn(
                                                        styleData.column).role,
                                                    parseFloat(staticT.text))
                                        isWriteable = false
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        GroupBox {
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            Layout.fillHeight: true
            implicitWidth: parent.width - 20
            implicitHeight: parent.bottom - 40 - paraG.bottom
            title: "试算结果"
            //            ColumnLayout {
            //                anchors.fill: parent
            ListFrame {
                id: listResult
                anchors.top: parent.top
                anchors.topMargin: 5
                anchors.left: parent.left
                //                anchors.leftMargin: 5
                anchors.right: parent.right
                //                anchors.rightMargin: 5
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 30
                tablelistName: listName
                //                border.width: 1

                //                Component.onCompleted: {

                //                    //                    listForceAbs.tableList.model = g_MainQuo.getRiskCustModel(
                //                    //                                "绝对强平", getCondition() + "#risk_grade=3")
                //                }
                onGridWidthChange: {
                    if (bInital && col >= 0) {
                        bChangeWidth = true
                        colCfg.setColumnWidth(
                                    listName,
                                    listResult.tableList.getColumn(col).role,
                                    listResult.tableList.getColumn(col).width)
                    }
                }
                onRightClick: {
                    rBtnMenu.row = row
                    rBtnMenu.col = col
                    rBtnMenu.model = listResult.tableList.model
                    rBtnMenu.popup()
                }
                Connections {
                    target: colSet
                    onUpdateUIColumn: {
                        if (sList == listName)
                            listResult.updateColumn(listName)
                    }
                }

                onLoadHeaderFinish: bInital = true
            }
            Component.onCompleted: console.log("GroupBox")
            //                Item {
            //                    Layout.preferredHeight: 10
            //                }
            PageRow {
                //            Rectangle {
                id: pageRow
                anchors.left: parent.left
                anchors.leftMargin: 10
                anchors.right: parent.right
                anchors.rightMargin: 10
                anchors.bottom: parent.bottom
                anchors.top: listResult.bottom
                anchors.topMargin: 5
                //                height: 30
                //                border.width: 1
                //                border.color: "red"
                //                color: "blue"
                //                z: 15
            }
            //            }
        }

        RowLayout {
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 5
            Layout.preferredHeight: 40
            //            Layout.alignment: Qt.AlignHCenter
            Button {
                text: "设置列"
                anchors.left: parent.left
                anchors.leftMargin: 25
                //                Layout.alignment: Qt.AlignHCenter
                //                Layout.alignment: Qt.AlignLeft | Qt.AlignTop
                onClicked: {
                    colSet.visible = true
                    colSet.refList = listResult
                    colSet.loadColumnCfg(listName)
                }
            }

            Item {
                Layout.fillWidth: true
            }
        }
    }
    Button {
        text: "关闭"
        anchors.right: parent.right
        anchors.rightMargin: 25
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        onClicked: closeTab(tabName)
    }
    function addCalcPara(prodCode, price) {
        calcParaModel.append({
                                 prod_code: prodCode,
                                 now_price: price,
                                 exch_long_rate: 0,
                                 exch_short_rate: 0,
                                 mem_long_rate: 0,
                                 mem_short_rate: 0
                             })
    }

    function freshResult() {
        var req = paramCalc
        req += pageRow.getReqPageInfo()

        var rsp = g_MainQuo.riskTestCalc(req)
        var msg = g_MainQuo.getPopMsg()
        if (msg.length > 0) {
            tipInput.text = msg
            tipInput.open()
            return
        }

        listResult.tableList.model = rsp.getAlmModel("cal_result", listName)

        pageRow.recordCount = rsp.get("total_record")
        pageRow.curPage = rsp.get("page_no")
    }

    ListModel {
        id: calcParaModel
    }
    //    ListModel {
    //        id: calcValueDrop
    //    }
    Timer {
        //改变列宽触发频繁，所以用定时保存
        id: timer_save_column
        interval: 50000
        repeat: true
        triggeredOnStart: true
        running: true
        onTriggered: {
            if (!bChangeWidth)
                return
            bChangeWidth = false
            colCfg.saveColumnWidth()
            console.log("save_column ")
        }
    }
}
